package org.jeecg.modules.simulator.model.train.event;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
;
import org.jeecg.modules.simulator.recorder.TrainRecorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @program: simulator-b20240918
 * @description:
 * @author: renzhg
 * @create: 2024-11-21 09:24
 **/
@Component
@Slf4j
public class TrainActionListenRecorder {
    private static final Logger logger = LoggerFactory.getLogger(TrainActionListenRecorder.class);

    public static final String COMMON_DIRECTORY = "D:/aaaaaa/stationjsonfile/";

    @EventListener
    public void recordActionTrain(TrainRecordEvent event) {
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        logger.info("TrainActionListenRecorder recordActionTrain");
        Map<String, TrainRecorder> trainActionRecordersList = (Map<String, TrainRecorder>) event.getSource();
        for (Map.Entry<String, TrainRecorder> entry : trainActionRecordersList.entrySet()) {
            String key = entry.getKey();
            TrainRecorder value = entry.getValue();
            File jsonFile = new File(COMMON_DIRECTORY + key + ".json");
            try {
                if (jsonFile.exists()) {
                    // 如果文件存在，则追加内容
                    FileWriter fileWriter = new FileWriter(jsonFile, true); // 以追加模式打开文件
                    fileWriter.write(objectMapper.writeValueAsString(value) + System.lineSeparator());
                    fileWriter.close();
                    System.out.println("Successfully appended to file: " + jsonFile.getAbsolutePath());
                } else {
                    // 如果文件不存在，则创建新文件并写入内容
                    objectMapper.writeValue(jsonFile, value);
                    System.out.println("Successfully created file: " + jsonFile.getAbsolutePath());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("Failed to write to file: " + jsonFile.getAbsolutePath());
            }

        }



    }
}
